<template>
  <div id="piechart">
        <div id="pie"></div>
        <div id="pieData">
           <el-input type="textarea" :rows="2"  v-model="pieDataS" @change="dataChange">
           </el-input>
           <el-button type="primary" plain @click="Sort">Sort</el-button>
           <div id='config'>
             <div id="innerRadius" class="config">
               <p>innerRadius(%):</p>
               <el-input-number v-model="innerRadius" @change="configChange" :step="5"
                :max="outerRadius - 5" :min="0"></el-input-number>
             </div>
             <div id="outerRadius" class="config">
               <p>outerRadius(%):</p>
               <el-input-number v-model="outerRadius" @change="configChange" :step="5"
                :max="100" :min="innerRadius + 5"></el-input-number>
             </div>
           </div>
        </div>
    </div>
</template>
<script>
import { PieChart } from './PieChart'
export default {
  name: 'PieChart',
  data () {
    return {
      pieData: [],
      itemsName: [],
      innerRadius: 0,
      outerRadius: 100,
      pieChart: {}
    }
  },
  created () {
    this.setPieData()
  },
  mounted () {
    this.pieChart = new PieChart('pie')
    this.pieChart.innerRadius = '0%'
    this.pieChart.outerRadius = '100%'
    console.log(this.itemsName)
    this.pieChart.itemsName = this.itemsName
    this.pieChart.title = 'PieChart'
    this.pieChart.data = this.pieData
    this.pieChart.draw()
  },
  computed: {
    pieDataS: {
      get: function () {
        return this.pieData.map(d => d.name + ':' + d.value).toString()
      },
      set: function (d) {
        let data = d.split(',')
        this.pieData = []
        for (let i = 0; i < data.length; ++i) {
          this.pieData.push({
            name: data[i].split(':')[0],
            value: parseInt(data[i].split(':')[1])
          })
        }
      }
    }
  },
  methods: {
    setPieData () {
      let num = parseInt(Math.random() * 3 + 6)
      for (let i = 0; i < num; ++i) {
        this.pieData.push({
          name: 'item-' + (i + 1),
          value: parseInt(Math.random() * 25 + 5)
        })
        this.itemsName.push('item-' + (i + 1))
      }
    },
    dataChange () {
      this.pieChart.data = this.pieData
      this.itemsName = []
      for (let i = 0; i < this.pieData.length; ++i) {
        this.itemsName.push('item-' + (i + 1))
      }
      this.pieChart.itemsName = this.itemsName
      this.pieChart.update()
    },
    configChange () {
      this.pieChart.innerRadius = this.innerRadius + '%'
      this.pieChart.outerRadius = this.outerRadius + '%'
      this.pieChart.update()
    },
    Sort () {
      this.pieData.sort((a, b) => a.value - b.value)
      this.pieChart.sort()
    }
  }
}
</script>
<style scoped>
#piechart {
    height: 100%;
    width: 100%;
}
#pie {
    height: 60%;
    width: 100%;
}
#pieData {
    height: 40%;
    width: 100%;
}
.config {
  float: left;
  width: 50%;
}
</style>
